package com.example.forumsystem.demos.web.service.impl;

import com.example.forumsystem.demos.web.common.ResultCode;
import com.example.forumsystem.demos.web.exception.ApplicationException;
import com.example.forumsystem.demos.web.mapper.ArticleInfoMapper;
import com.example.forumsystem.demos.web.mapper.ArticleReplyInfoMapper;
import com.example.forumsystem.demos.web.model.ArticleReplyInfo;
import com.example.forumsystem.demos.web.model.Result;
import com.example.forumsystem.demos.web.service.IArticleReplyService;
import com.example.forumsystem.demos.web.service.IArticleService;
import com.example.forumsystem.demos.web.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ArticeReplyServiceImpl implements IArticleReplyService {
    @Autowired
    private ArticleReplyInfoMapper articleReplyInfoMapper;
    @Autowired
    private IArticleService articleService;

    @Transactional
    @Override
    public void create(ArticleReplyInfo articleReply) {
        if (articleReply == null || articleReply.getArticleId() == null
                || articleReply.getPostUserId() == null
                || StringUtil.isEmpty(articleReply.getContent())) {
            log.warn("参数校验失败，文章id为:" + articleReply.getArticleId()
                    + ", 回复的用户id为: " + articleReply.getPostUserId()
                    + ", 回复的内容为:" + articleReply.getContent());
            throw new ApplicationException(Result.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 设置默认值
        articleReply.setReplyId(null);
        articleReply.setReplyUserId(null);
        articleReply.setLikeCount(0);
        articleReply.setState((byte) 0);
        articleReply.setDeleteState((byte) 0);
        Date date = new Date();
        articleReply.setCreateTime(date);
        articleReply.setUpdateTime(date);

        int row = articleReplyInfoMapper.insertSelective(articleReply);
        if (row != 1) {
            log.warn("回复新增失败");
            throw new ApplicationException(Result.fail(ResultCode.ERROR_SERVICES));
        }

        articleService.addOneReplyCountById(articleReply.getArticleId());
        log.info("回复成功");

    }

    @Override
    public List<ArticleReplyInfo> selectByArticleId(Long articleId) {
        if (articleId == null || articleId <= 0) {
            log.warn("参数校验失败，传来的文章id为:" + articleId);
            throw new ApplicationException(Result.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        return articleReplyInfoMapper.selectByArticleId(articleId);
    }
}
